var confirmorderEvent = function() {};

confirmorderEvent.prototype = {

	changeAddress: function(addresses) {
		//没有收货地址，新增
		if (0 == addresses.length) {
			$(".main").on("click", "#addNewAddress", function() {
				redirect("../account/addAddress.html?fromConfirmOrder=true");
			});
		}
		//选择其他收货地址，新增
		$("#addresses_pop").on("click", "#addNewAddressInAddressPop", function() {
			redirect("../account/address.html?fromConfirmOrder=true");
		});
		//选择其他地址
		$("#defaultAddress").on("click", "#selectAddress", function() {
			$("#pop_back").show();
			$("#addresses_pop").show();
			setTimeout(function() {
				$("#addresses_pop").addClass("moveFromBottom-moved");
			}, 200);
		});
		//取消选择
		$("#cancelSelect,#pop_back").on("click", function() {
			$("#addresses_pop").removeClass("moveFromBottom-moved");
			setTimeout(function() {
				$("#addresses_pop").hide();
				$("#pop_back").hide();
			}, 200);
		});
		//从地址列表中选择一个，填充当前收货地址
		$("#addresses_pop").on("click", "div[name='address']", function() {
			var tip = $(this).attr("tip");
			var j = 0;
			var address = {};
			var defaultAddress = [];
			while (addresses[j]) {
				address = addresses[j];
				if (tip == address.id) {
					defaultAddress.push('<div tip="' + address.id + '" id="address_id" class="shdzk' + (address.def_flag ? '' : '1') + ' mbtopbottom">');
					defaultAddress.push('<p class="dwei"><img src="../../images/ditutb' + (address.def_flag ? '' : '1') + '.png"></p>');
					defaultAddress.push('<div class="shdzhi">');
					defaultAddress.push('<p class="sjrmc"><span>' + address.mobile + '</span>' + (address.def_flag ? '<b class="mrziti">[默认]</b>' : '') + '收件人：' + address.consignee + '</p>');
					defaultAddress.push('<p>' + address.address + '</p>');
					//html.push('<p><span>发票：无</span>备注：请发圆通快递</p>');
					defaultAddress.push('<p  class="sjrmc"><span><b class="ybzt"></b><i class="iconfont icon-jiantou2"></i></span><span id="selectAddress">选择其他收货地址</span></p>');
					defaultAddress.push('</div>');
					defaultAddress.push('</div>');
					$("#defaultAddress").html(defaultAddress.join(''));
					$("#addresses_pop").removeClass("moveFromBottom-moved");
					setTimeout(function() {
						$("#addresses_pop").hide();
						$("#pop_back").hide();
					}, 200);
					break;
				}
				j++;
			}
			console.log(1);
		});
	},
	//支付配送
	chooseDeliver: function(user, data) {

		$("#main").on("click", "#deliver_p", "click", function() {
			$("#pop_back").show();
			$("#deliver_pop").show();
			setTimeout(function() {
				$("#deliver_pop").addClass("moveFromBottom-moved");
			}, 200);
		});
		//取消选择
		$("#cancelSelectDelivery,#pop_back").on("click", function() {
			$("#deliver_pop").removeClass("moveFromBottom-moved");
			setTimeout(function() {
				$("#deliver_pop").hide();
				$("#pop_back").hide();
			}, 200);
		});

		var isChecked;
		var selfAddressLength = $("input[name='DeliverAddress']").ength;
		$("#deliver_pop").on("click", "input[name='DeliverAddress']", function() {
			isChecked = $(this).is(":checked");
			if (isChecked) {
				$("#deliver_pop #helponself").attr("checked", true);
				$("#deliver_pop #delivery").attr("checked", false);
				$("#deliver_pop #helponself+label").addClass('checkboxFour_checked');
			}

		});

		$("#deliver_pop").on("click", "#delivery", function() {
			isChecked = $(this).is(":checked");
			if (isChecked) {
				$("#deliver_pop input[name='DeliverAddress']").attr("checked", !isChecked);
				$("#deliver_pop input[name='DeliverAddress']+label").removeClass('checkboxFour_checked');
				$("#deliver_pop #helponself+label").removeClass('checkboxFour_checked');
			}
		});

		$("#deliver_pop").on("click", "#helponself", function() {
			isChecked = $(this).is(":checked");
			$("#deliver_pop input[name='DeliverAddress']").attr("checked", isChecked);
			if (isChecked) {
				$("#deliver_pop input[name='DeliverAddress']+label").addClass('checkboxFour_checked');
			}
		});

		//确定配送方式
		$("#deliver_pop").on("click", "#commitDelivery", function() {
			var deliverType = $("#deliverPoint input[name='DeliveryType']:checked").val();
			if (undefined == deliverType) {
				$.toast("请选择配送方式");
				return;
			} else if ("2" == deliverType) {
				if ("" == $("#deliverPoint #deliveryPhone").val()) {
					$.toast("请填写配送电话");
					return;
				}
				if ("" == $("#deliverPoint #deliveryName").val()) {
					$.toast("请填写配姓名");
					return;
				}
				if (!isTelephone($("#deliverPoint #deliveryPhone").val())) {
					$.toast("配送电话格式不正确");
					return;
				}
			}
			if ('1' == deliverType) {
				$("#deliver_p #chosedDeliverType").html('普通快递');
				$("#deliver_pop").removeClass("moveFromBottom-moved");
				setTimeout(function() {
					$("#deliver_pop").hide();
					$("#pop_back").hide();
				}, 200);
			} else {
				var deliverStr = '[自提货]' + $("#deliverPoint input[name='DeliverAddress']:checked").attr('tip');
				deliverStr = deliverStr.substr(0, 16) + '***';
				$("#deliver_p #chosedDeliverType").html(deliverStr);
				var addressData = {
					addressid: $(this).attr("tip"),
					memberid: user.id,
					organizeid: $("#deliver_pop input[name='DeliverAddress']:checked").attr('id').match(/\d{4,}/)[0],
					consignee: $("#deliver_pop #deliveryName").val(),
					mobile: $("#deliver_pop #deliveryPhone").val(),
				};
				$.ajax({
					type: "POST",
					url: CONFIG_MANAGER.RequstUrl + "v1/member/address/editdelivery/" + user.id,
					async: true,
					data: JSON.stringify(addressData),
					contentType: 'application/json',
					beforeSend: function() {
						$.showWaiting();
					}
				}).done(function(data) {
					$("#deliver_pop").removeClass("moveFromBottom-moved");
					setTimeout(function() {
						$("#deliver_pop").hide();
						$("#pop_back").hide();
					}, 200);
					$("#deliver_pop #commitDelivery").attr("tip", data.id);
				}).always(function() {
					$.closeWaiting();
				});
			}

		});
	},	
	//优惠券
	useCoupon:function(user, data){
		
		//选择
		$("#selectCoupon").on("click", function(){
			var html = [];
			$.each(data.usable_coupon, function(i, coupon) {				
				var tips = {serial_no:coupon.serial_no, title:coupon.title, is_usable:coupon.is_usable};
				
				html.push('<div name="item_coupon" class="shp-gwcny_center">');
				html.push('<p class="shp-ms shp-ms1">优惠券</p>');
				html.push('<p class="shp-coudan">'+ coupon.title +'</p>');
				html.push('<p name="use_coupon" tips='+ JSON.stringify(tips) +' class="ob-cha-select"><a style="width:58px;" class="receive_button">使用</a></p>');
				html.push('</div>');			
			});

			html.push('<div class="shp-gwcny_center">');
			html.push('<p id="no_coupon" class="ob-cha-select"><a style="width:58px;border:1px solid #c6c6c6;color:#c6c6c6" class="receive_button">取消使用</a></p>');
			html.push('</div>');
			$('#active_item').html(html.join(''));
			
			$("#pop_back").show();
			$("#couponPop").show();			
			setTimeout(function() {
				$("#couponPop").addClass("moveFromBottom-moved");
			}, 200);
		});
		
		//点击使用
		$("#active_item").on("click", "p[name=use_coupon]", function(){
			var tips = JSON.parse($(this).attr('tips'));
			$("#main #couponTitle").html(tips.title);
			$("#main #coupon_serial_no").val(tips.serial_no);
			$("#couponPop").removeClass("moveFromBottom-moved");
			setTimeout(function() {
				$("#couponPop").hide();
				$("#pop_back").hide();
			}, 200);			
		});
		
		//不使用
		$("#active_item").on("click", "#no_coupon", function(){
			$("#main #couponTitle").html("选择优惠券");
			$("#main #coupon_serial_no").val("");
			$("#couponPop").removeClass("moveFromBottom-moved");
			setTimeout(function() {
				$("#couponPop").hide();
				$("#pop_back").hide();
			}, 200);			
		});
		
		//取消选择
		$("#cancelCoupon").on("click", function(){ 
				$("#couponPop").removeClass("moveFromBottom-moved");
				setTimeout(function() {
					$("#couponPop").hide();
					$("#pop_back").hide();
				}, 200);			
		});
	},	
	//提交订单
	commitOrder: function(user, data) {
		//提交订单
		$("#commit_order").on("click", function() {
			if ($("#main #defaultAddress #addNewAddress") && $("#main #defaultAddress #addNewAddress").length > 0) {
				$.toast("请添加收货地址");
				var _main = ("fixed" == $(".main").css("position")) ? $(".main") : $(window);
				if (os.ios) {
					_main.animate({
						scrollTop: '0px'
					}, 500);
				} else {
					$("body, html").animate({
						scrollTop: 0
					}, 500);
				}
				return;
			}

			var total_coin = parseInt($("#total_coin").html());
			var currentLoginUser = getLocalStorage(STORAGE_MANAGER.currentmember);
			if (total_coin > currentLoginUser.coin) {
				$.toast("您的星币不够，不能购买");
				return;
			}
			var requestData = getLocalStorage(STORAGE_MANAGER.confirmOrderData);
			var deliverType = $("input[name='DeliveryType']:checked").val();
			//普通快递
			if (undefined == deliverType || '1' == deliverType) {
				requestData.delivery = 1;
				requestData.delivery_point = 3101;
				requestData.address_id = $("#address_id").attr('tip');
			}
			//自提货
			else if ('2' == deliverType) {
				requestData.delivery = 0;
				requestData.delivery_point = 3102;
				requestData.address_id = data.delivery_point[0].id;;
			}
			requestData.coupono = $("#main #coupon_serial_no").val();
			requestData.invoice_title = $('input[name="invoice"]').val(),
			requestData.invoice_remark = $('input[name="remark"]').val(),			
			requestData.supplier = [];
			$.each($("div[id^=supplier_]"), function(i, span) {
				var tips = JSON.parse($(span).attr('tip'));
				var supplierModel = {	stock_id: tips.stock_id,};
				requestData.supplier.push(supplierModel);
			});
			$.ajax({
				type: "POST",
				url: CONFIG_MANAGER.RequstUrl + "v1/order/create",
				async: true,
				data: JSON.stringify(requestData),
				contentType: 'application/json',
				beforeSend: function() {
					$.showWaiting();
				}
			}).done(function(data) {
				//console.log("order:" + JSON.stringify(data));
				//更新购物车商品个数
				if ('0' == requestData.instant_buy) {
					var i = 0;
					var totalQty = 0;
					while (requestData.target_id[i]) {
						totalQty += requestData.target_id[i].qty;
						i++;
					}
					//生成订单后重新计算购物车所有商品数量
					$.ajax({
						type: "GET",
						headers: {
							token: user.token
						},
						url: CONFIG_MANAGER.RequstUrl + "v1/cart/sum/" + user.id,
						async: true,
					}).done(function(data) {
						setLocalStorage(STORAGE_MANAGER.cacheproductcount, data.count);
						if (AGENT_CLIENT.APP) {
							plus.webview.getWebviewById("../home/main.html").evalJS("getShopcartProductCount()");
							plus.webview.getWebviewById('../shopcart/shoppingcart.html').evalJS("shoppingcartPageReady()");
						}
					});
				}
				redirect("payCenter.html?mainorderno=" + data[0].main_order_no);
			}).fail(function(data) {
				$.toast(data.responseJSON.Message);
			}).always(function() {
				$.closeWaiting();
			});
		});
	},

}